package com.ynet.middleground.riskmanage.utils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

import com.ynet.middleground.riskmanage.bean.hangxin.YkccxReq;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.google.common.base.Throwables;
import com.ynet.core.exception.BusinessException;
import com.ynet.core.log.IfpLogger;
import com.ynet.file.service.FileService;
import com.ynet.file.starter.FileServiceConfiguration;

/**
 * @author liulx
 * @description 文件工具
 * @date 2020-08-02 23:19
 */
public class FileUtil {

    @Autowired
    static FileServiceConfiguration fileServiceConfiguration;

    @Autowired
    static FileService fileService;

    /**
     * 获取文件后缀，不带 .
     * 
     * @param fileUrl 文件地址
     * @return 文件后缀，不带点.
     */
    public static String getFileSuffix(String fileUrl) {
        if (StringUtils.isBlank(fileUrl)) {
            return null;
        }
        // 从最后一个点之后截取字符串
        return fileUrl.substring(fileUrl.lastIndexOf(".") + 1);
    }

    /**
     * 根据文件 OSS 地址获取文件
     * 
     * @param fileUrl oss 地址
     * @param suffix 文件后缀
     * @return 文件对象
     */
    public static File getFileByUrl(String fileUrl, String suffix) {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        BufferedOutputStream stream = null;
        InputStream inputStream = null;
        File file = null;
        try {
            URL imageUrl = new URL(fileUrl);
            HttpURLConnection conn = (HttpURLConnection)imageUrl.openConnection();
            conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            inputStream = conn.getInputStream();

            byte[] buffer = new byte[1024];
            int len = 0;

            while ((len = inputStream.read(buffer)) != -1) {
                outStream.write(buffer, 0, len);
            }

            file = File.createTempFile("pattern", suffix);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            stream = new BufferedOutputStream(fileOutputStream);
            stream.write(outStream.toByteArray());

        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "读取文件异常, case: {}",
                Throwables.getStackTraceAsString(e));
            throw new BusinessException("读取文件异常", "ECCT0006");
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (stream != null) {
                    stream.close();
                }
                outStream.close();
            } catch (Exception e) {
            }
        }
        return file;
    }

    /**
     * 将文件转换成 byte[]
     * 
     * @param tradeFile 待转换文件
     * @return 文件 byte[]
     */
    public static byte[] fileToByte(File tradeFile) {
        byte[] buffer = null;
        FileInputStream fis = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try {
            fis = new FileInputStream(tradeFile);
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            buffer = bos.toByteArray();
        } catch (Exception e) {
            IfpLogger.error(Thread.currentThread().getStackTrace()[1].getMethodName(), "读取文件异常, case: {}",
                Throwables.getStackTraceAsString(e));
            throw new BusinessException("读取文件异常", "ECCT0006");
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                bos.close();

            } catch (Exception e) {
            }
        }
        return buffer;
    }

    /**
     * 根据文件短路径获得文件完整地址
     *
     * @param shortOssUrl 文件短路径地址
     *            {@link FileService#uploadFile(java.lang.String, java.io.InputStream, java.lang.String, java.lang.String)}
     *            eg: zhogntai/test.pdf
     * @return oss 完整路径 eg: http://oss-cn-qingdao-qdg-d01-a.cloud.qdport.com/zhongtai/test.pdf
     */
    public static String getOssFullUrl(String endpoint, String shortOssUrl) {
        // String endpoint = fileServiceConfiguration.getConfigs().get(0).getOssConfig().getEndpoint();
        return endpoint.substring(0, endpoint.lastIndexOf("/")) + "/" + shortOssUrl;
    }

    public static void main(String[] args) {
        YkccxReq y = new YkccxReq();
        y.setNsrsbh("1212");
        y.setFjh("11");
        y.setFpzl("42");
        String xml = XStreamUtil.converTomXml(y);
        System.out.println(xml);
    }
}
